layui.use(['form', 'jquery'], function () {

    const form = layui.form,
        $ = layui.jquery;

    let userCode = sessionStorage.getItem("pmsUserCode");
    findAllRole();
    findByCode(userCode);

    /**
     * 查询单个
     * @param userCode
     */
    function findByCode(userCode) {

        let result = commonAjax(AUTH_SERVER_URL+'/userRoleRelation/findByUserCode', {userCode: userCode}, 'get');
        $('#userCode').val(userCode);
        if (result.data !== null) {
            setData(result.data);
        }
    }

    /**
     * 赋值
     */
    function setData(data) {
        $('#roleCode').val(data.roleCode);
        form.render();
    }

    /**
     * 保存
     */
    form.on('submit(commit)', function (data) {

        let formData = JSON.stringify(data.field);
        let result = commonAjax(AUTH_SERVER_URL+'/user/distributeRole', formData, 'post');
        if (result.code === 200) {
            layerMsgSaveSuccess();
        } else {
            layerMsgSaveFail();
        }
        return false;
    });

    /**
     * 查询所有角色
     */
    function findAllRole() {
        let result = commonAjax(AUTH_SERVER_URL+'/role/findRoleList', '', 'get');
        let html = '<option value="">请选择</option>';
        for (let i = 0; i < result.data.length; i++) {
            html += '<option value="' + result.data[i].code + '">' + result.data[i].name + '</option>';
        }
        $("#roleCode").html(html);
        form.render();
    }
});